#include "SimpleDial.h"
#include <iostream>
#include <math.h>


SimpleDial::SimpleDial() {


	color = 0.8;
	arc_angle = 1.0;
	add_events(Gdk::POINTER_MOTION_MASK | Gdk::BUTTON_PRESS_MASK | Gdk::BUTTON_RELEASE_MASK);
	buttonPressed = false;
}


SimpleDial::~SimpleDial() {



}

bool SimpleDial::on_button_press_event(GdkEventButton* event) {


	if (event->button == 1) {

		m_drag_y = int(event->y);

		buttonPressed = true;
		color = 0.1;
		queue_draw();


	}

	return true;

}


bool SimpleDial::on_button_release_event(GdkEventButton* event) {


	color = 0.6;

	buttonPressed = false;
	queue_draw();
	return true;


}


bool SimpleDial::on_motion_notify_event(GdkEventMotion* event) {


	if (buttonPressed) {

		int y_diff = int(event->y) - m_drag_y;
		arc_angle = map_value(y_diff);

		std::cout << "x: " << arc_angle << std::endl;

	}

	queue_draw();

	return true;

}

int SimpleDial::polToCar_x () {

	int phi = (int)ceil(arc_angle*360);

	int x = (int) ceil ( r  * (cos(phi* (M_PI/180)))); 

	return x; 
}

int SimpleDial::polToCar_y () {

	int phi = (int) ceil(arc_angle*360);

	int y = (int) ceil(r * (sin(phi * (M_PI/180)))); 


	return y;
}


float SimpleDial::map_value(int value) {

	if (value > 0) {

		if (value > 100) return 0.0;

		else return 0.5 - ( ((float)value/100.0) * 0.5 ) ;



	}

	else if (value < 0) {


		if (value < -100) return 1.0;

		else return ((float)value * -1 /100.0) * 0.5 + 0.5;

	}

	else if (value == 0) {

		return 0.5;
	}

	return 0.0;
}





bool SimpleDial::on_expose_event(GdkEventExpose* event)
{

	Glib::RefPtr<Gdk::Window> window = get_window();
	
	if (window)	{
		
		Gtk::Allocation allocation = get_allocation();
		const int width = allocation.get_width();
		const int height = allocation.get_height();
		int lesser = MIN(width, height);
		r = lesser / 6.0;

		// coordinates for the center of the window
		int xc, yc;
		xc = width / 2;
		yc = height / 2;

		Cairo::RefPtr<Cairo::Context> cr = window->create_cairo_context();
		cr->set_line_width(lesser * 0.02);  


		cr->rectangle(event->area.x, event->area.y,	event->area.width, event->area.height);
		cr->clip();

		// first draw fixed arc
		cr->save();
		cr->arc(width / 5.0, height / 4.0, r, 0.0,  360 * (M_PI/180));
		cr->set_source_rgb(0.0, 0.8, 0.0);
		cr->restore();  // back to opaque black
		cr->stroke();   // outline it

		// first arc depending on value if knob
		cr->save();
		cr->set_source_rgb(0.8, 0.0, 0.0);
		cr->arc(width / 5.0, height / 4.0, r, 0.0,  (arc_angle*360) * (M_PI/180));
		cr->stroke();   // outline it


		// draw line
		cr->restore();  // back to opaque black
		cr->move_to(width / 5.0, height / 4.0);
		cr->line_to(polToCar_x() + (width / 5.0), polToCar_y() + height/4.0);
		cr->stroke();

	}

	return true;
}
